package com.maysev.myjob_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maysev.myjob_backend.common.R;
import com.maysev.myjob_backend.entity.Company;
import com.maysev.myjob_backend.entity.Recruiter;
import com.maysev.myjob_backend.service.CompanyService;
import com.maysev.myjob_backend.service.RecruiterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 五七
 * @create 2023-04-02 14:12
 * @description:
 */
@RestController
@Slf4j
@CrossOrigin("http://localhost:8082")
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private RecruiterService recruiterService;
    @GetMapping()
    private R<Company> getComInfo(@RequestParam Long userId){
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getUserId,userId);
        Company one = companyService.getOne(queryWrapper);
        if (one == null){
            return R.error("未绑定公司");
        }
        return R.success(one);
    }

    /**
     * 添加或修改
     * @param company
     * @return
     */
    @PostMapping
    private R<String> submitComInfo(@RequestBody Company company){
        //1. 检查公司表中是否已存在该用户绑定的公司
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getUserId,company.getUserId());
        Company one = companyService.getOne(queryWrapper);
        // 2.1没有
        if (one == null){
            //保存公司
            companyService.save(company);
            //获取新保存的公司信息
            Company newOne = companyService.getOne(queryWrapper);
            //找到招聘人信息
            LambdaQueryWrapper<Recruiter> companyLambdaQueryWrapper = new LambdaQueryWrapper<>();
            companyLambdaQueryWrapper.eq(Recruiter::getId,company.getUserId());
            Recruiter recruiter = recruiterService.getOne(companyLambdaQueryWrapper);
            //将招聘人的公司Id绑定新保存的公司id
            recruiter.setCompanyId(newOne.getId());
            //更新招聘人信息
            recruiterService.updateById(recruiter);
            //在招聘人表中绑定公司id
            return R.success("添加成功");

        }
        //2.2 有,更新
        companyService.update(company,queryWrapper);
        return R.success("修改成功");
    }
}
